from flask import Flask, jsonify, request
import requests
import json
from flask_cors import CORS
import os
import datetime

app = Flask(__name__)
# 修改CORS配置，允许所有接口跨域访问
CORS(app, resources={r"/*": {"origins": "http://localhost:63342"}})

# 配置参数
product_id = "AN3Cn8YJxb"
device_name = "location"
authorization = "version=2022-05-01&res=userid%2F426834&et=1746219046&method=sha1&sign=zlhPnuQ2qPGR9BBu6Tl%2FHWxqTHw%3D"

@app.route('/')
def home():
    return "Welcome to the Smart Cane API! Use /get-location to fetch device location."

@app.route('/get-location', methods=['GET'])
def get_location():
    url = "https://iot-api.heclouds.com/thingmodel/query-device-property"
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Authorization": authorization
    }
    params = {
        "product_id": product_id,
        "device_name": device_name
    }

    try:
        response = requests.get(url, headers=headers, params=params)
        print("Status Code:", response.status_code)
        print("Response Text:", response.text)  # 打印响应内容

        response_data = json.loads(response.text)

        if "data" in response_data and response_data["data"] is not None:
            for item in response_data["data"]:
                if item["identifier"] == "cur_location":
                    cur_location = json.loads(item["value"])
                    return jsonify(cur_location)
            return jsonify({"error": "未找到 cur_location 属性"})
        else:
            return jsonify({"error": "响应中未包含 data 字段或 data 为 None"})

    except Exception as e:
        return jsonify({"error": str(e)})


@app.route('/save-route', methods=['POST'])
def save_route():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "No data provided"}), 400

        # 将导航路径信息保存到文件中
        save_path = os.path.join(os.getcwd(), "saved_routes")  # 使用绝对路径
        if not os.path.exists(save_path):
            print(f"Creating directory: {save_path}")
            os.makedirs(save_path)
            print(f"Directory created successfully at: {os.path.abspath(save_path)}")

        # 生成文件名
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"route_{timestamp}.json"
        filepath = os.path.join(save_path, filename)

        # 保存文件
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

        return jsonify({"message": "Route data saved successfully", "filepath": filepath}), 200
    except Exception as e:
        print(f"Error occurred: {str(e)}")
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)